const loaderUtils = require("loader-utils");
const babel = require('@babel/core')
const DefaultData = require("../utils/DefaultData.js");
const UtilsIndex = require("../utils/index.js");

let defaultOptions = {
  getPlugins: () => {
    return DefaultData.jsAstPlugins
  },
  ignoreDirOrFile: DefaultData.ignoreDirOrFile
}

class PriUtils {
  static getPageScript(pageCode) {
    const load = UtilsIndex.getHtmlLoad(pageCode)
    return load('script').html()
  }

  static changeScriptCode(scriptCode, plugins) {
    const ast = babel.parse(scriptCode, {
      sourceType: 'module',
      configFile: false,
      plugins
    })
    const {code: changeResult} = babel.transformFromAstSync(ast, null, {
      configFile: false,
      plugins
    });
    return changeResult
  }
}

function supportForDecorators(source, map) {
  // 获取到用户给当前 Loader 传入的 options
  defaultOptions = Object.assign(defaultOptions, loaderUtils.getOptions(this))
  const plugins = defaultOptions.getPlugins()
  const {resourcePath} = this
  if (defaultOptions.ignoreDirOrFile(resourcePath)) {
    return source
  }
  if (resourcePath.endsWith('.js')) {
    source = PriUtils.changeScriptCode(source, plugins)
  } else if (resourcePath.endsWith('.vue')) {
    const script = PriUtils.getPageScript(source)
    const changeScript = PriUtils.changeScriptCode(script, plugins)
    source = source.replace(script, '\n' + changeScript + '\n')
  }
  return source
}

module.exports = supportForDecorators
